<!--
 @description 验收图片上传
 @fileName CheckImageItem.vue
 @author zengqiongying
 @created 2023/06/15 16:07:43
-->
<template>
  <div class="upload-img">
    <qmp-image v-if="imageUrl" width="100%" height="100%" fit="contain" :src="imageUrl" @click.stop="onPreviewImage" />
    <template v-if="!readonly">
      <template v-if="imageUrl">
        <div :class="['btn', 'btn-del', deleteClassName]" @click.stop="onClickDelete">
          <slot name="delete"> </slot>
        </div>
      </template>
      <template v-else>
        <div v-if="!hideUpload" class="btn btn-camera" @click.stop="onClickCamera">
          <slot name="trigger"> </slot>
        </div>
        <input ref="fileEl" id="file-input" type="file" style="display: none" @change="handlerFileChange" />
      </template>
    </template>
  </div>
</template>

<script lang="ts">
  import { ref, defineComponent, reactive, toRefs, watch, getCurrentInstance } from 'vue'
  import { useStore } from 'vuex'
  import { formatURL, parseTime } from '@/utils'
  import { postImageUpload, queryServerTime } from '@/apis/common'
  import { ImagePreview } from 'qmp-component'
  import { fileToBase64, dataURLtoBlob, imageProcessing } from '@/utils/imageProcessing'

  export default defineComponent({
    name: 'CheckImageUpload',
    props: {
      modelValue: {
        type: String,
        default: ''
      },
      caid: {
        // 验收ID
        type: String,
        default: ''
      },
      readonly: {
        type: Boolean,
        default: false
      },
      hideUpload: {
        type: Boolean,
        default: false
      },
      deleteClassName: {
        // 删除按钮样式
        type: String,
        default: ''
      }
    },
    emits: ['update:modelValue', 'update:imageName', 'delete'],
    setup(props, { emit }) {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const fileEl = ref()
      const datas = reactive({
        imageUrl: ''
      })
      watch(
        () => props.modelValue,
        (val) => {
          datas.imageUrl = formatURL(val)
        },
        {
          immediate: true
        }
      )

      const handlerFileChange = (e: any) => {
        if (e.target.files.length === 0) {
          return
        }
        for (const file of e.target.files) {
          // uploader(file)
          const type = file.type.replace('image/', '')
          const name = file.name
          fileToBase64(file).then((base64: any) => {
            // 将文件转换为base64
            handleImageWaterMark('jpeg', name, base64)
          })
        }
      }

      // 删除图片
      const onClickDelete = () => {
        emit('update:modelValue', '')
        emit('delete')
      }
      // 手机拍照
      const onClickCamera = () => {
        if (process.env.QMP_EVN === 'development') {
          fileEl.value.value = null
          fileEl.value.click()
          return
        }
        proxy
          .$nativeHandler('openCamera')
          .then(async (res: any) => {
            /* const files = (res.data || []).map((e: any) => {
              return new File([dataURLtoBlob(e)], `${new Date().getTime()}.${res.type}`, {
                type: `image/${res.type}`
              })
            })
            // 成功
            for (const file of files) {
              uploader(file)
            } */

            const type = 'jpeg' //res.type
            const name = `${new Date().getTime()}.${type}`
            const base64 = `data:image/${type};base64,${res.data[0]}`
            handleImageWaterMark(type, name, base64)
          })
          .catch((err: any) => {
            console.log(err)
          })
          .finally(() => {
            // 完成
          })
      }
      // 处理图片水印
      const handleImageWaterMark = async (type: string, name: string, imgUrl: string) => {
        const loading = proxy.$loading({ message: '图片处理中,请等待...' })
        let nowTime = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
        await queryServerTime().then((res: any) => {
          // 获取水印内容
          if (res.success === 1 && res.data) {
            nowTime = res.data
          }
        })
        const userName = $store.getters.userInfo.userName
        const watermarkContent = [nowTime, userName]
        imageProcessing(type, imgUrl, watermarkContent, (blob: any) => {
          const file = new File([blob], name, {
            type: `image/${type}`
          })
          loading.close()
          uploader(file)
        })
      }
      const uploader = (file: any) => {
        const data = new FormData()
        // 验收id(必填)
        const otherParams = {
          caid: props.caid,
          ImgOriginName: file.name
        }
        /*  data.append('ImgCustomName', '') // 自定义名称(必填)
         */
        data.append('data', JSON.stringify(otherParams))
        data.append('file', file)
        postImageUpload(data)
          .then((res) => {
            const url = res.data.sysFileUrl
            emit('update:modelValue', url)
            emit('update:imageName', otherParams.ImgOriginName)
          })
          .catch(() => {
            proxy.$toast('文件上传失败!')
          })
      }
      // 大图预览
      const onPreviewImage = () => {
        if (datas.imageUrl) {
          ImagePreview([datas.imageUrl])
        }
      }

      return {
        ...toRefs(datas),
        fileEl,
        onClickDelete,
        onClickCamera,
        handlerFileChange,
        onPreviewImage
      }
    }
  })
</script>
<style lang="less" scoped>
  .upload-img {
    position: relative;
    width: 100%;
    height: 100%;
    background: var(--bg-global-weak);
    border-radius: var(--radius-l);
    overflow: hidden;
    /deep/ .qmp-image__error,
    .qmp-image__loading {
      background-color: var(--bg-global-weak);
    }
    .btn {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 40px;
      height: 40px;
      background-repeat: no-repeat;
      background-position: center;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .btn-del {
      background-color: rgba(255, 255, 255, 0.4);
      border-radius: 36px;
      background-size: 24px 24px;
      background-image: url('~@/assets/images/icon-del-solid.png');
    }
    .btn-camera {
      background-size: 24px 24px;
      background-image: url('~@/assets/images/icon-camera.png');
    }
  }
</style>
